package com.vader.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author kaivader
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        InetSocketAddress inetAddress = new InetSocketAddress("127.0.0.1", 6667);
        if (!socketChannel.connect(inetAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("建立连接中，可进行其他操作");
            }
        }

        while (true) {
            String str = "client connected";
            ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
            socketChannel.write(byteBuffer);
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            socketChannel.write(ByteBuffer.wrap(next.getBytes(StandardCharsets.UTF_8)));
            if (next.equalsIgnoreCase("quit")){
                break;
            }
        }
    }
}
